import type { ApiResponse } from '../../../types';

/**
 * 商品详情数据接口
 */
interface ProductDetail {
  id: number;
  name: string;
  gd_description: string;
  gd_keywords: string;
  picture: string;
  retail_price: number;
  actual_price: number;
  in_stock: number;
  sales_volume: number;
  buy_limit_num: number;
  buy_prompt: string;
  description: string;
  type: number;
  is_open: number;
  category_name: string;
  category_id: number;
  created_at: string;
}

/**
 * 获取商品详情API接口
 * @param event - Nuxt事件对象
 * @returns 商品详情数据
 */
export default defineEventHandler(async (event): Promise<ApiResponse<ProductDetail | null>> => {
  try {
    // 获取商品ID参数
    const productId = getRouterParam(event, 'id');
    
    if (!productId || isNaN(Number(productId))) {
      return {
        success: false,
        message: '商品ID参数无效'
      };
    }

    // 获取数据库连接
    const db = event.context.cloudflare.env.DB as D1Database;
    if (!db) {
      console.error('D1数据库绑定未在事件上下文中找到');
      return {
        success: false,
        message: '服务器配置错误，数据库不可用'
      };
    }

    // 查询商品详情，包含分类信息
    const result = await db.prepare(`
      SELECT 
        g.id,
        g.gd_name,
        g.gd_description,
        g.gd_keywords,
        g.picture,
        g.retail_price,
        g.actual_price,
        g.in_stock,
        g.sales_volume,
        g.buy_limit_num,
        g.buy_prompt,
        g.description,
        g.type,
        g.is_open,
        g.created_at,
        gr.name as category_name,
        gr.id as category_id
      FROM goods g
      LEFT JOIN groups gr ON g.group_id = gr.id
      WHERE g.id = ? AND g.deleted_at IS NULL
    `).bind(productId).first();

    if (!result) {
      return {
        success: false,
        message: '商品不存在或已下架'
      };
    }

    // 检查商品是否启用
    if (result.is_open !== 1) {
      return {
        success: false,
        message: '商品已下架'
      };
    }

    // 格式化商品数据
    const productDetail: ProductDetail = {
      id: Number(result.id) || 0,
      name: String(result.gd_name || ''),
      gd_description: String(result.gd_description || ''),
      gd_keywords: String(result.gd_keywords || ''),
      picture: String(result.picture || ''),
      retail_price: Number(result.retail_price) || 0,
      actual_price: Number(result.actual_price) || 0,
      in_stock: Number(result.in_stock) || 0,
      sales_volume: Number(result.sales_volume) || 0,
      buy_limit_num: Number(result.buy_limit_num) || 0,
      buy_prompt: String(result.buy_prompt || ''),
      description: String(result.description || ''),
      type: Number(result.type) || 1,
      is_open: Number(result.is_open) || 0,
      category_name: String(result.category_name || '未分类'),
      category_id: Number(result.category_id) || 0,
      created_at: String(result.created_at || '')
    };

    // 为了兼容前端组件，添加image字段
    const responseData = {
      ...productDetail,
      image: productDetail.picture
    };

    return {
      success: true,
      message: '获取商品详情成功',
      data: responseData
    };

  } catch (error) {
    console.error('获取商品详情错误:', error);
    return {
      success: false,
      message: '获取商品详情失败，请稍后重试'
    };
  }
});